﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MsgEntity;
using System.Collections;
using System.Data;
using System.IO;
using CommonLib;

namespace CommunicationLib
{
    /* 此处按照8位为一个BYTE的换算，因文档里使用的为位，所以需把文档里的位换算成BYTE后
        * 再进行字节数的格式化，否则报文长度就不对。刚开始时在这个位置吃了亏，后来参考JAVA版
        * 的DEMO才明白。还有就是报文长度packlength虽把自己也算进去，即由开始的AA55一直到最后
        * 的CRC较验的两个BYTE前为止含packlength值来进行CRC较验计算，但packlength的值是包含由
        * AA55到最后含CRC较验在内的所有字节长度。否则报文长度值不对也不行。 陈斌 2017-11-09 */

    public class SendMsgOper :  Communicator
    {

        public bool SendMsg(HeartBeat info)
        {
            if (Connected)
            {
                HeartBeat beat = new HeartBeat();
                beat.RealsaleCode = "专资办分派的用户ID";
                beat.Datetime = DateTime.Now.Date;
                MessageEntity msg = new MessageEntity();
                beat.PayloadId = SetData(new byte[] { (byte)MessageType.HeartBeat }, (int)MessageItem.PayloadId);
                beat.MessageId = SetData(BitConverter.GetBytes(Communicator.SendCount), (int)MessageItem.MessageId);
                beat.PeerId = SetData(BitConverter.GetBytes(0), (int)MessageItem.PeerId);
                byte[] realsaleCode = SetData(Encoding.UTF8.GetBytes(beat.RealsaleCode), (int)HeartBeatItem.RealsaleCode);
                byte[] datetime = SetData(Encoding.UTF8.GetBytes(beat.Datetime.ToString("yyyy-MM-ddTHH:mm:ss")), (int)HeartBeatItem.Datetime);
                int datalength = 16 + 8 + 16 + 8 + 32 + 32 + 16 + realsaleCode.Length + datetime.Length;
                beat.PacketLength = SetData(BitConverter.GetBytes(datalength), (int)MessageItem.PacketLength);
                List<byte[]> datalist = new List<byte[]>();
                datalist.Add(beat.SyncTag);
                datalist.Add(beat.Version);
                datalist.Add(beat.PacketLength);
                datalist.Add(beat.PayloadId);
                datalist.Add(beat.MessageId);
                datalist.Add(beat.PeerId);
                datalist.Add(realsaleCode);
                datalist.Add(datetime);

                datalist.Add(SetData(BitConverter.GetBytes(Crc16(MergeData(datalist))), 16));
                
                //var client = ConnectBase.GetConnect;
                //client.Write(MergeData(datalist));                
                
            }
            return true;
        }

        public bool SendMsg(Auth info)
        {                             
            Auth entity = new Auth();
            entity.Username = "专资办分派的用户ID";
           // entity.Username = "";
            entity.Password = GeneralTools.Md5Encrpyt("专资办分派的密码");
            entity.SoftwareMd5 = "";
            entity.RawdataCount = 100;
            entity.PayloadId = new byte[] { (byte)MessageType.Auth };
            entity.MessageId = BitConverter.GetBytes(Communicator.SendCount);
            Communicator.SendCount++;
            entity.PeerId = BitConverter.GetBytes(0);
            entity.MessageId = SetData(new byte[] { (byte)1 }, (int)MessageItem.MessageId);
            byte[] username = SetData(Encoding.Default.GetBytes(entity.Username), (int)AuthItem.Username);
            byte[] password = SetData(Encoding.Default.GetBytes(entity.Password), (int)AuthItem.Password);
            byte[] softwareMd5 = SetData(new byte[] { (byte)0 }, (int)AuthItem.SoftwareMd5);
            byte[] rawdataCount = SetData(BitConverter.GetBytes(entity.RawdataCount), (int)AuthItem.RawdataCount);

            List<byte[]> datalist = new List<byte[]>();
            datalist.Add(entity.SyncTag);
            datalist.Add(entity.Version);
            //.Add(entity.packet_length);
            byte[] packlength = BitConverter.GetBytes(entity.SyncTag.Length + entity.Version.Length + entity.PayloadId.Length
              + entity.MessageId.Length + entity.PeerId.Length + username.Length + password.Length + softwareMd5.Length
              + rawdataCount.Length + 4);
            datalist.Add(new byte[] { packlength[0] });
            datalist.Add(new byte[] { packlength[1] });
            datalist.Add(entity.PayloadId);
            datalist.Add(entity.MessageId);
            datalist.Add(entity.PeerId);
            datalist.Add(username);
            datalist.Add(password);
            datalist.Add(softwareMd5);
            datalist.Add(rawdataCount);
            byte[] crcCode = BigToLittle(BitConverter.GetBytes(Crc16(MergeData(datalist))));

            datalist.Add(new byte[] { crcCode[3] });
            datalist.Add(new byte[] { crcCode[2] });
            
           
            byte[] cc = MergeData(datalist);        
           
            int bb = CInit_message_callback(MsgCallBackDelegate);
            int aa = CSend_message(cc, cc.Length);
          
                return true;
        }

        public bool SendMsg(UploadRecord info)
        {
            info.PayloadId = new byte[] { (byte)MessageType.Updata };
            info.MessageId = BitConverter.GetBytes(Communicator.SendCount);
            Communicator.SendCount++;
            info.PeerId = BitConverter.GetBytes(0);
            info.MessageId = SetData(new byte[] { (byte)1 }, (int)MessageItem.MessageId);            
            UploadRecordContent content = new UploadRecordContent
            {
                business_date = DateTime.Parse("2017-09-20 17:40:12"),
                cinema_code = "44008201",
                code = "2017092043574768",
                datetime = DateTime.Now,
                film_code = "051201532017",
                online_sale = 1,
                onlinesale_code = "99140258",
                operation = 1,
                price = 48,
                screen_code = "3",
                seat_code = "0000000000003726",
                service = 13,
                session_code = "42647118",
                session_datetime = DateTime.Parse("2017-9-20 20:00:00")
            };
            byte[] count = SetData(1, (int) UpdataItem.Count);
            byte[] businessDate = SetData(Encoding.Default.GetBytes(content.business_date.ToString("yyyy-MM-dd")),
                (int)UpdataItem.business_date);
            byte[] cinemaCode = SetData(content.cinema_code, (int)UpdataItem.cinema_code);
            byte[] code = SetData(content.code, (int)UpdataItem.code);
            byte[] datetime = SetData(content.datetime, (int)UpdataItem.datetime);
            byte[] filmCode = SetData(content.film_code, (int)UpdataItem.film_code);
            byte[] onlineSale = SetData(content.online_sale, (int)UpdataItem.online_sale);
            byte[] onlineSaleCode = SetData(content.onlinesale_code, (int)UpdataItem.onlinesale_code);
            byte[] operation = SetData(content.operation, (int)UpdataItem.operation);
            byte[] price = SetData(content.price, (int)UpdataItem.price);
            byte[] screenCode = SetData(content.screen_code, (int)UpdataItem.screen_code);
            byte[] seatCode = SetData(content.seat_code, (int)UpdataItem.seat_code);
            byte[] service = SetData(content.service, (int)UpdataItem.service);
            byte[] sessionCode = SetData(content.session_code, (int)UpdataItem.session_code);
            byte[] sessionDateTime = SetData(content.session_datetime, (int)UpdataItem.session_datetime);

            List<byte[]> msgData = new List<byte[]>();
            msgData.Add(count);
            msgData.Add(businessDate);
            msgData.Add(cinemaCode);
            msgData.Add(onlineSale);
            msgData.Add(screenCode);
            msgData.Add(filmCode);
            msgData.Add(sessionCode);
            msgData.Add(sessionDateTime);
            msgData.Add(operation);
            msgData.Add(code);
            msgData.Add(seatCode);
            msgData.Add(price);
            msgData.Add(service);
            msgData.Add(onlineSale);
            msgData.Add(datetime);
            byte[] rawData = MergeData(msgData);
            GetSignature(rawData);

            return true;
        }      

        public string TestCrc()
        {
            List<byte> testbyte2 = new List<byte>();
            string teststr2 = "aa55016f003700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
            for (int i = 0; i < teststr2.Length / 2; i++)
            {
                string b = teststr2.Substring((2 * i), 2);
                byte a = (byte)uint.Parse(b, System.Globalization.NumberStyles.HexNumber);
                testbyte2.Add(a);
            }
            byte[] bbbb = testbyte2.ToArray();
            return Crc16(bbbb).ToString();

           
        }
    }   
}
